<template>
  <div>
    <el-dialog :visible="visible" title="Detail" :show-close="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
        <!-- Name -->
        <el-form-item label="Name" prop="name" label-width="100px">
          <el-input v-model="form.name" placeholder="Name" maxlength="20" show-word-limit />
        </el-form-item>
        <!-- Intro -->
        <el-form-item label="Intro" prop="intro" label-width="100px">
          <el-input v-model="form.intro" type="textarea" maxlength="200" show-word-limit placeholder="Intro" />
        </el-form-item>
        <!-- Operation -->
        <div style="text-align:right;">
          <el-button type="danger" @click="handleCancel">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">Confirm</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'CourseDetail',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    data: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {},
      rules: {
        name: [
          { required: true, message: 'name must exist', trigger: 'blur' }
        ],
        intro: [
          { min: 1, max: 200, message: 'we recommend the length between 1 and 200' }
        ]
      }
    }
  },
  watch: {
    data: {
      handler(newVal) {
        this.form = newVal
      }
    }
  },
  methods: {
    handleCancel() {
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
      this.$emit('cancel')
    },
    handleConfirm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          this.$emit('confirm', this.form)
          this.$refs.form.resetFields()
          this.$refs.form.clearValidate()
        } else {
          this.$message.error('form validate failed')
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
